"""
Case Type   : 兼容M*数据库datetime数据类型
Case Name   : datetime类型和interval类型运算
Create At   : 2023.09.13
Owner       : z@wan005
Description :
    1、创建兼容b库
    2、datetime类型和interval类型运算
    3、清理环境
Expect      :
    1、成功
    2、成功
    3、成功
History     :modified by zhanghuan96，2024.6.22，修改断言，适配最新代码
            :modified by zhanghuan96，2024.7.12，告警提示变更
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class CompatibilityTest0020(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.db_name = "db_datetime_0020"

    def test_datetime(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '--step1:创建兼容b库;expect:成功--'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} dbcompatibility 'b';"
        self.log.info(sql_cmd)
        sql_res = self.sh_primary.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res,
                      '执行失败:' + text)

        text = '--step2:datetime类型和interval类型运算;expect:成功--'
        self.log.info(text)
        sql_cmd = f'''select datetime '294277-01-09 04:00:00' \
                - interval '4 hours' as result;'''
        self.log.info(sql_cmd)
        sql_res = self.sh_primary.execut_db_sql(sql_cmd,
                                                dbname=self.db_name)
        self.log.info(sql_res)
        self.assertIn('WARNING:  date/time field overflow',
                      sql_res, '执行失败:' + text)
        sql_cmd = f'''
        select datetime '2001-09-29 03:00' - datetime '2001-09-27 12:00' \
        as result;
        select datetime '9998-12-31 23:59:59'+ interval '4 hours' as result;'''
        self.log.info(sql_cmd)
        sql_res = self.sh_primary.execut_db_sql(sql_cmd,
                                                dbname=self.db_name)
        self.log.info(sql_res)
        res_list = ['1910000', '9999-01-01 03:59:59']
        for res in res_list:
            self.assertIn(res, sql_res, '执行失败:' + text)

    def tearDown(self):
        text = '----step3:清理环境;expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop database {self.db_name};"
        self.log.info(sql_cmd)
        drop_res1 = self.sh_primary.execut_db_sql(sql_cmd,
                                                  dbname='postgres')
        self.log.info(drop_res1)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_res1,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
